package com.jiantong.work.impl.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jiantong.user.impl.dao.BreedFactoryDao;
import com.jiantong.user.impl.dao.ButcherFactoryDao;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.ButcherFactory;
import com.jiantong.work.enums.PrintRelativeInfo;
import com.jiantong.work.impl.dao.CertNumberDao;
import com.jiantong.work.impl.manager.AnimalCertificateManager;
import com.jiantong.work.model.BreedReport;
import com.jiantong.work.model.BreedReportSurveyRecord;
import com.jiantong.work.model.CertNumber;
import com.jiantong.work.model.IssuanceTable;
import com.jiantong.work.service.AnimalCertificateService;
import com.jiantong.work.util.CertificateUtil;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.Response;
import io.terminus.common.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 动物AB证,开证工具类
 * Created by mz03 on 2017/5/2.
 */
@Slf4j
@Service
@RpcProvider
public class AnimalCertificateServiceImpl implements AnimalCertificateService{

    private static final String ZZLX = "3";                                                                                              //1:A证,3:B证
    private static final String JYLX = "1";                                                                                              //1:产地检疫  2- 挎县分销动物检疫  4-其它系统对接
    private static final String FLAG = "DONG_YANG";
    private static final String COMMAND = "71";
    private static final String SERVICE = "4";
    private static final String USER_ID = "28540";
    private static final String CREDENTIAL_URL = "http://114.215.249.190:8080/app/app?";

    private final BreedFactoryDao breedFactoryDao;
    private final CertNumberDao certNumberDao;
    private final ButcherFactoryDao butcherFactoryDao;
    private AnimalCertificateManager animalCertificateManager;

    @Autowired
    public AnimalCertificateServiceImpl(BreedFactoryDao breedFactoryDao,
                                        CertNumberDao certNumberDao,
                                        ButcherFactoryDao butcherFactoryDao,
                                        AnimalCertificateManager animalCertificateManager) {
        this.breedFactoryDao = breedFactoryDao;
        this.certNumberDao = certNumberDao;
        this.butcherFactoryDao = butcherFactoryDao;
        this.animalCertificateManager = animalCertificateManager;
    }

    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();

    @Override
    public  Response<IssuanceTable> isSucceed(BreedReport breedReport,
                                              BreedReportSurveyRecord breedReportSurveyRecord){

        CertNumber certNumber = certNumberDao.randomFind();
        if (certNumber == null){
            log.error("开证编号读取失败,请检查是否号段已用完");
            return Response.fail("开证编号读取失败,请检查是否号段已用完");
        }
        //检疫证号
        String jyhgzmbh = buildJyhgzmbh();

        Map<String ,Object> requestBody = buildRequestBody(breedReport,breedReportSurveyRecord,jyhgzmbh);

        String credentialUrl = CREDENTIAL_URL;

        for (String key : requestBody.keySet()) {
            credentialUrl += (key + "=" + requestBody.get(key) + "&");
        }
//        try {
//            URL url = new URL(credentialUrl);
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.connect();
//            int code = connection.getResponseCode();
//            if (code != 200) {
//                log.error("发生其它错误，认证服务器返回"+ code);
//                return Response.fail(code + "错误");
//            }
//            InputStream is = connection.getInputStream();
//            byte[] response = new byte[is.available()];
//            is.read(response);
//            is.close();
//            if (response.length == PrintRelativeInfo.HTTP_FAILED_RESULT_STATUS.value()) { //此时开证编号有问题,需要修改状态为已使用  没通过  证号编码有问题
//                log.error("认证无效，找不到此次认证的会话信息！");
//                return Response.fail("认证无效，找不到此次认证的会话信息！");
//            }
//            String userId = new String(response, "UTF-8");
//
//            //打印返回结构
//            Map<String , String> resultMap = objectMapper.readValue(userId, new TypeReference<Map<String , String>>(){});
//            String result_code = resultMap.get("code"); //  0 为失败; 1 为成功
//
//            //判断是否成功, 成功改变isSucceed为true
//            if (result_code.equals("0")){
//                //此时开证编号有问题,需要修改状态为已使用
//                return Response.fail("认证无效，编码无效！");
//            }

        IssuanceTable issuanceTable = buildIssuanceTable(requestBody,breedReport,breedReportSurveyRecord);
        certNumber.setCertStatus(PrintRelativeInfo.CERT_UNUSED_STATUS.value());
        issuanceTable = animalCertificateManager.handle(issuanceTable,certNumber);
        return Response.ok(issuanceTable); //返回一个打印表实体类对象

//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//            return Response.fail("认证失败!");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Response.fail("认证失败！");
//        }
    }

    private IssuanceTable buildIssuanceTable(Map<String, Object> requestBody ,
                                             BreedReport breedReport,
                                             BreedReportSurveyRecord breedReportSurveyRecord) {
        IssuanceTable issuanceTable = new IssuanceTable();

        issuanceTable.setAnimalTypeId((String) requestBody.get("animalTypeId"));
        issuanceTable.setXqbsxx((String) requestBody.get("xqbsxx"));
        issuanceTable.setYt(CertificateUtil.useS(breedReport.getPurposeType()));
        issuanceTable.setZzlx(ZZLX);
        issuanceTable.setCommand(COMMAND);
        issuanceTable.setFlag(FLAG);
        issuanceTable.setGgdw((String) requestBody.get("ggdw"));
        issuanceTable.setHzLxdh((String) requestBody.get("hzLxdh"));
        issuanceTable.setHzName((String) requestBody.get("hzName"));
        issuanceTable.setJyhgzmbh((String) requestBody.get("jyhgzmbh"));
        issuanceTable.setJylx(JYLX);
        issuanceTable.setMddCslx((String) requestBody.get("mddCslx"));
        issuanceTable.setMddRegionId((String) requestBody.get("mddRegionId"));
        issuanceTable.setMddRegionName((String) requestBody.get("mddRegionName"));
        issuanceTable.setMddXxdz((String) requestBody.get("mddXxdz"));
        issuanceTable.setQfsj((String) requestBody.get("qfsj"));
        issuanceTable.setQfUserName((String) requestBody.get("qfUserName"));
        issuanceTable.setQydCslx((String) requestBody.get("qydCslx"));
        issuanceTable.setQydRegionId((String) requestBody.get("qydRegionId"));
        issuanceTable.setQydRegionName((String) requestBody.get("qydRegionName"));
        issuanceTable.setQydXxdz((String) requestBody.get("qydXxdz"));
        issuanceTable.setSbztRegionId((String) requestBody.get("sbztRegionId"));
        issuanceTable.setService(SERVICE);
        issuanceTable.setSl((String) requestBody.get("sl"));
        issuanceTable.setUserId(USER_ID);

        //新加的字段
        issuanceTable.setReportId(breedReport.getId());
        issuanceTable.setQfUserId(breedReportSurveyRecord.getVetUserId());
        issuanceTable.setAnimalType(CertificateUtil.kindName(breedReport.getBreedType()));
        issuanceTable.setGgdwName(CertificateUtil.unitShiftName(breedReport.getUnit()));
        issuanceTable.setCertStatus(PrintRelativeInfo.PRINT_UNUSED_STATUS.value());

        return issuanceTable;

    }


    private Map<String ,Object> buildRequestBody(BreedReport breedReport ,
                                                 BreedReportSurveyRecord breedReportSurveyRecord,
                                                 String jyhgzmbh){
        //目的地
        String mddRegionId = "000000000000";
        String mddRegionName = "";
        String mddXxdz = "";
        ButcherFactory butcherFactory = null;
        if(breedReport.getIsToLocal() == -1){
            mddRegionName = breedReport.getReceiveAddress();
            mddXxdz = mddRegionName;
        }else {
            butcherFactory = butcherFactoryDao.findById(breedReport.getButcherFactoryId());
            long provinceId = butcherFactory.getProvinceId();
            long cityId = butcherFactory.getCityId();
            long regionId = butcherFactory.getRegionId();
            long streetId = butcherFactory.getStreetId();
            mddRegionId = buildString(provinceId,cityId,regionId,streetId);
            mddRegionName = butcherFactory.getRegion() + "市";
            mddXxdz = butcherFactory.getDetail() + "," + butcherFactory.getName();
        }
        String mddCslx = CertificateUtil.BUTCHER_FACTORY + "";
        //货主
        String hzName = breedReport.getOwner();
        String hzLxdh = breedReport.getOwnerMobile();

        String animalTypeId = CertificateUtil.kind(breedReport.getBreedType())+"";                                      //动物种类id 82:猪
        String sl = breedReportSurveyRecord.getQualifiedQuantity()+"";                                                  //数量
        String ggdw = CertificateUtil.unitShift(breedReport.getUnit())+"";


        BreedFactory breedFactory = breedFactoryDao.findById(breedReport.getBreedFactoryId());
        String qydRegionId = "";
        String qydRegionName = breedFactory.getRegion();

        String qydXxdz = "南漳县" + breedReport.getDeliverAddress() + "," + breedFactory.getName();
        if(breedReport.getDeliverAddress().equals(breedFactory.getDetail())){
            long provinceId = breedFactory.getProvinceId();
            long cityId = breedFactory.getCityId();
            long regionId = breedFactory.getRegionId();
            long streetId = breedFactory.getStreetId();
            qydRegionId = buildString(provinceId,cityId,regionId,streetId);
        }else {
            qydRegionId = "000000000000";
        }
        String qydCslx = CertificateUtil.BREED_FACTORY+"";

        String yt = CertificateUtil.use(breedReport.getPurposeType()) + "";                                               //用途
        String xqbsxx = breedReport.getEarTagNumber();
        long provinceId = breedFactory.getProvinceId();
        long cityId = breedFactory.getCityId();
        long regionId = breedFactory.getRegionId();
        long streetId = breedFactory.getStreetId();
        String sbztRegionId = buildString(provinceId,cityId,regionId,streetId);

        String qfsj = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss").format(new Date());

        String qfUserName = breedReportSurveyRecord.getVetUserName();

        Map<String ,Object> requestBody = Maps.newHashMap();
        requestBody.put("command",COMMAND);
        requestBody.put("service",SERVICE);
        requestBody.put("userid",USER_ID);
        requestBody.put("jyhgzmbh",jyhgzmbh);
        requestBody.put("zzlx",ZZLX);
        requestBody.put("jylx",JYLX);
        requestBody.put("flag",FLAG);
        requestBody.put("hzName",hzName);
        requestBody.put("hzLxdh",hzLxdh);
        requestBody.put("animalTypeId",animalTypeId);
        requestBody.put("sl",sl);
        requestBody.put("ggdw",ggdw);
        requestBody.put("qydRegionId",qydRegionId);
        requestBody.put("qydRegionName",qydRegionName);
        requestBody.put("qydXxdz",qydXxdz);
        requestBody.put("qydCslx",qydCslx);
        requestBody.put("yt",yt);
        requestBody.put("xqbsxx",xqbsxx);
        requestBody.put("qfsj",qfsj);
        requestBody.put("sbztRegionId",sbztRegionId);
        requestBody.put("mddRegionId",mddRegionId);
        requestBody.put("mddRegionName",mddRegionName);
        requestBody.put("mddXxdz",mddXxdz);
        requestBody.put("mddCslx",mddCslx);
        requestBody.put("qfUserName",qfUserName);

        return requestBody;
    }


    private String buildString(long provinceId,long cityId,long regionId,long streetId){
        String str = "";

        if(provinceId <10L){
            str = str + 0 + provinceId;
        }else {
            str += provinceId + "";
        }
        if(cityId <10L){
            str = str + 0 + cityId + "";
        }else {
            str += cityId + "";
        }
        if(regionId <10L){
            str = str + 0 + regionId + "";
        }else {
            str += regionId + "";
        }
        if(streetId <10L){
            str = str + 0 + streetId + "";
        }else {
            str += streetId + "";
        }

        str += "0000";
        return str;
    }

    private String buildJyhgzmbh(){
        StringBuilder jyhgzmbh = new StringBuilder();

        Random random = new Random();
        while (jyhgzmbh.length()<10){
            jyhgzmbh.append(random.nextInt(10));
        }
        return jyhgzmbh.toString();
    }
}
